package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.UserLoginBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/3 10:43
 */
public class Dws_04_DwsUserUserLoginWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindowApp().init("Dws_4_DwsUserUserLoginWindowApp",
                                                    4004,
                                                    1,
                                                    "Dws_4_DwsUserUserLoginWindowApp",
                                                    "Dws_4_DwsUserUserLoginWindowApp",
                                                    Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 先过滤登录数据:
        // 1.1 uid不等于null(表示已经登录)
        // 且 1.2 last_page_id ==null 表示在入口页面实现的登录
        //   或 1.3 上个页面id是 login 表示在上个页面完成的登录
        SingleOutputStreamOperator<JSONObject> loginStream = filterLogingData(stream);
        // 2. 找到登录和回流记录, 封装到JavaBean中
        SingleOutputStreamOperator<UserLoginBean> loginAndBackStream = findLoginAndBack(loginStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> aggregatedStream = windowAndAggregate(loginAndBackStream);
        // 4. 写出到clickhouse 中
        writeToClickHouse(aggregatedStream);
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserLoginBean> stream) {
        stream.addSink(FlinkSinkUtil.getClickHouseSink("gmall2022",
                                                       "dws_user_user_login_window",
                                                       UserLoginBean.class
        ));
        
        
    }
    
    private SingleOutputStreamOperator<UserLoginBean> windowAndAggregate(
        SingleOutputStreamOperator<UserLoginBean> stream) {
        return stream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean v1,
                                                UserLoginBean v2) throws Exception {
                        v1.setBackCt(v1.getBackCt() + v2.getBackCt());
                        v1.setUuCt(v1.getUuCt() + v2.getUuCt());
                        
                        return v1;
                    }
                },
                new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void process(Context context,
                                        Iterable<UserLoginBean> elements,
                                        Collector<UserLoginBean> out) throws Exception {
                        
                        String stt = DateFormatUtil.toYmdHms(context.window().getStart());
                        String edt = DateFormatUtil.toYmdHms(context.window().getEnd());
                        
                        UserLoginBean userLoginBean = elements.iterator().next();
                        
                        userLoginBean.setStt(stt);
                        userLoginBean.setEdt(edt);
                        userLoginBean.setTs(System.currentTimeMillis());
                        
                        out.collect(userLoginBean);
                        
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<UserLoginBean> findLoginAndBack(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                
                private ValueState<String> lastLoginDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    /*
                    首先要知道: 在这里处理的数据已经都是登录数据了
                    1. 用状态记录最后一次登录时间(年月日)
                    2. 如果这次登录时间与状态不一致, 则这次就是今天首次登录
                    
                    3. 如果状态不为空, 并同今天不是同一天: 证明以前登录过
                        判断是否为7日回流用户:  今天-最后一次登录 >=8
                     */
                    String lastLoginDate = lastLoginDateState.value();
                    String today = DateFormatUtil.toDate(obj.getLong("ts"));
                    
                    
                    long uuCt = 0L;
                    long backCt = 0L;
                    // 1. 找到今天登录记录
                    if (!today.equals(lastLoginDate)) {
                        uuCt = 1L;
                    }
                    
                    // 2. 找到回流记录
                    if (lastLoginDate != null && !today.equals(lastLoginDate)) {
                        if ((DateFormatUtil.toTs(today) - DateFormatUtil.toTs(lastLoginDate)) / 1000 / 60 / 60 / 24 >= 8) {
                            backCt = 1L;
                        }
                    }
                    
                    if (uuCt == 1L) { // 只要今天有登录, 就应该输出
                        out.collect(new UserLoginBean("", "", backCt, uuCt, obj.getLong("ts")));
                        lastLoginDateState.update(today);
                    }
                }
            });
        
        
    }
    
    private SingleOutputStreamOperator<JSONObject> filterLogingData(DataStreamSource<String> stream) {
        /*
            过滤出登录数据:
            1. 打开应用后自动登录
                    登录操作发生在入口页面 last_page_id is null ，所以保入口页面即可
            2. 打开应用没有登录, 浏览部分页面的时候跳转到登录页面
                    这种情况, 保留登录之后的页面即可: last_page_id = login
                    
            
         */
        
        return stream
            .map(JSON::parseObject)
            .filter(obj ->
                        obj.getJSONObject("common").getString("uid") != null
                            && (obj.getJSONObject("page").getString("last_page_id") == null || obj.getJSONObject("page").getString("last_page_id").equals("login"))
            );
    }
}
